package com.example.cofeed.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ada.common.util.CustomHelper;
import com.baoyz.actionsheet.ActionSheet;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ObjectUtils;
import  com.example.cofeed.util.ToastUtils;;
import com.bumptech.glide.Glide;
import com.example.cofeed.R;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseActivity;
import com.example.cofeed.base.TakePhotoActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.entity.JsonBean;
import com.example.cofeed.entity.User;
import com.example.cofeed.widget.GetJsonDataUtil;
import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;

import org.devio.takephoto.model.TResult;
import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class EditUserInfoActivity extends TakePhotoActivity {
    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_company)
    EditText mEtCompany;
    @BindView(R.id.et_contact)
    EditText mEtContact;
    @BindView(R.id.et_tel)
    EditText mEtTel;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.tv_addr)
    TextView mTvAddr;
    @BindView(R.id.et_addr_info)
    EditText mEtAddrInfo;
    @BindView(R.id.et_ppa)
    EditText mEtPpa;
    private String mImgsrc;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_user_info;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        setMainTitle("编辑");
        setMainSubTitle("完成", 0);

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        ApiService.userinfo_get_edit(this, new DialogCallback<LzyResponse<List<User>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<List<User>>> response) {
               User user = response.body().data.get(0);
               if (ObjectUtils.isNotEmpty(user)){
                   Glide.with(mContext).load(user.picture).into(mIvAvatar);
                   mEtName.setText(user.name);
                   mEtCompany.setText(user.company);
                   mEtContact.setText(user.linkman);
                   mEtTel.setText(user.tel);
                   mEtPhone.setText(user.mobile);
                   mEtAddrInfo.setText(user.address);
                   mEtPpa.setText(user.mainproduct);
                   sheng = user.province;
                   shi = user.city;
                   qu = user.area;
                   mTvAddr.setText(sheng + shi + qu);

                   mImgsrc = user.picture;

               }

            }
        });

    }

    @Override
    protected void onRightClickAction() {
        super.onRightClickAction();

        String name = mEtName.getText().toString().trim();
        String company = mEtCompany.getText().toString().trim();
        String contact = mEtContact.getText().toString().trim();
        String tel = mEtTel.getText().toString().trim();
        String phone = mEtPhone.getText().toString().trim();
        String addrInfo = mEtAddrInfo.getText().toString().trim();
        String ppa = mEtPpa.getText().toString().trim();

        if (ObjectUtils.isEmpty(name)){
            showToast("请输入姓名");
            return;

        }
        if (ObjectUtils.isEmpty(company)){
            showToast("请输入公司名称");
            return;

        }
        if (ObjectUtils.isEmpty(contact)){
            showToast("请输入联系人");
            return;

        }
        if (ObjectUtils.isEmpty(tel)){
            showToast("请输入电话");
            return;

        }
        if (ObjectUtils.isEmpty(phone)){
            showToast("请输入手机号码");
            return;

        }
        if (ObjectUtils.isEmpty(sheng)){
            showToast("请选择省市区");
            return;

        }
        if (ObjectUtils.isEmpty(addrInfo)){
            showToast("请输入详细地址");
            return;

        }
        if (ObjectUtils.isEmpty(ppa)){
            showToast("请输入主营产品");
            return;

        }

        ApiService.save_userinfo(this, mImgsrc, name, company, contact, tel, phone, addrInfo, ppa, sheng, shi, qu, new DialogCallback<LzyResponse<Object>>(this) {
            @Override
            public void onSuccess(Response<LzyResponse<Object>> response) {
                showToast();
                finish();
            }
        });



    }

    @OnClick({R.id.layout_avatar, R.id.tv_addr})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_avatar:
                showActionSheet();
                break;
            case R.id.tv_addr:
                if (isLoaded) {
                    showPickerView();
                } else {
                    ToastUtils.showShort("正在解析");
                }
                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };


    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private boolean isLoaded = false;

    private String sheng;
    private String shi;
    private String qu;
    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                sheng  = options1Items.get(options1).getName();
                shi  = options2Items.get(options1).get(options2);
                qu  = options3Items.get(options1).get(options2).get(options3);

                mTvAddr.setText(sheng+shi+qu);
            }
        })


                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        final String imagePath = result.getImages().get(0).getCompressPath();
        ApiService.uploader(this, new File(imagePath), new DialogCallback<LzyResponse<Map<String, String>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
                mImgsrc = Uri.decode(response.body().data.get("imgsrc"));
                Glide.with(mContext).load(imagePath).into(mIvAvatar);

            }
        });

    }

    private void showActionSheet() {
        setTheme(R.style.ActionSheetStyleiOS7);
        ActionSheet
                .createBuilder(this, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("拍照", "从相册选择").setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                CustomHelper.TakePhoto(getTakePhoto(), CustomHelper.PICK_BY_TAKE, true);
                                break;
                            case 1:
                                CustomHelper.TakePhoto(getTakePhoto(), CustomHelper.PICK_BY_SELECT, true);
                                break;
                            default:
                        }
                    }
                }).show();

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
